package com.etooling.pdm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etooling.framework.entity.Employee;
import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.repository.EmployeeRepository;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.WebUtils;
import com.etooling.pdm.entity.Goods;
import com.etooling.pdm.entity.GoodsSpecs;
import com.etooling.pdm.entity.GoodsSpecsPropSetting;
import com.etooling.pdm.entity.GoodsSpecsPropValues;
import com.etooling.pdm.repository.*;
import com.etooling.pdm.service.GoodsSpecsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GoodsSpecsServiceImpl implements GoodsSpecsService {


    @Autowired
    GoodsSpecsRepository goodsSpecsRepository;
    @Autowired
    EmployeeRepository employeeRepository;
    @Autowired
    GoodsSpecsPropValuesRepository goodsSpecsPropValuesRepository;
    @Autowired
    GoodsTypeRepository goodsTypeRepository;
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    GoodsPropValuesRepository goodsPropValuesRepository;
    @Autowired
    GoodsPropRenameRulesRepository goodsPropRenameRulesRepository;


    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class)
    public ReplyObj add(HttpServletRequest request, String json) {
        try {
            JSONObject jsonObject = JSON.parseObject(json);
            String goodsId = jsonObject.getString("goodsId");
            if (WebUtils.checkStr(goodsId)) {
                String skuCode = jsonObject.getString("skuCode");
                Goods goods = goodsRepository.getById(goodsId);
                if (!WebUtils.checkStr(skuCode)) {
                    return WebUtils.flushFailure("没有唯一编码，无法添加");
                }
                String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
                Integer count = goodsSpecsRepository.countSkuCode(skuCode, companyId, GoodsSpecs.STATUS_DELETE, goods.getGoodsType().getIsProduct());
                if (count > 0) {
                    return WebUtils.flushFailure("唯一编码“" + skuCode + "”已经被占用了，无法添加此规格");
                }

                GoodsSpecs goodsSpecs = new GoodsSpecs();
                goodsSpecs.setCompanyId(companyId);

                goodsSpecs.setGoods(goods);
                goodsSpecs.setSkuCode(skuCode);
                String name = jsonObject.getString("name");
                goodsSpecs.setName(name);
                String specsNames = jsonObject.getString("specsNames");
                goodsSpecs.setSpecsNames(specsNames);
                String specsValues = jsonObject.getString("specsValues");
                goodsSpecs.setSpecsValues(specsValues);
                String memo = jsonObject.getString("memo");
                goodsSpecs.setMemo(memo);
                String imgId = jsonObject.getString("imgId");
                goodsSpecs.setImgId(imgId);
                String imgUrl = jsonObject.getString("imgUrl");
                goodsSpecs.setImgUrl(imgUrl);


                goodsSpecs.setStatus(GoodsSpecs.STATUS_RUNNING);
                String loginId = WebUtils.getSessionValue(request, WebUtils.LOGIN_USER_KEY);
                Employee creator = new Employee();
                creator.setId(loginId);
                goodsSpecs.setCreator(creator);
                Employee modifier = new Employee();
                modifier.setId(loginId);
                goodsSpecs.setModifier(modifier);
                goodsSpecs.setCreateTime(new Date());
                goodsSpecs.setLastModifiedTime(new Date());

                goodsSpecsRepository.save(goodsSpecs);

                JSONArray propList = jsonObject.getJSONArray("propList");
                List<GoodsSpecsPropValues> list = new ArrayList<>();
                for (int i = 0; i < propList.size(); i++) {
                    JSONObject prop = propList.getJSONObject(i);

                    String id = prop.getString("id");
                    String code = prop.getString("code");
                    String pValue = prop.getString("value");

                    GoodsSpecsPropValues goodsSpecsPropValues = new GoodsSpecsPropValues();
                    goodsSpecsPropValues.setGoods(goods);
                    goodsSpecsPropValues.setGoodsSpecs(goodsSpecs);
                    GoodsSpecsPropSetting setting = new GoodsSpecsPropSetting();
                    setting.setId(id);
                    goodsSpecsPropValues.setGoodsSpecsPropSetting(setting);
                    goodsSpecsPropValues.setCode(code);
                    goodsSpecsPropValues.setValue(pValue);
                    list.add(goodsSpecsPropValues);
                }
                goodsSpecsPropValuesRepository.saveAll(list);

                Boolean needReturn = jsonObject.getBoolean("needReturn");
                if (needReturn != null && needReturn) {
                    return WebUtils.flushSuccess(goodsSpecs);
                }
                return WebUtils.flushSuccess();
            } else {
                return WebUtils.flushFailure("没有选择对应产品");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return WebUtils.flushFailure("添加规格时，数据不能成功解析");
        }
    }


    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class)
    public ReplyObj update(HttpServletRequest request, String json) {
        try {
            JSONObject jsonObject = JSON.parseObject(json);
            String id = jsonObject.getString("id");
            if (!WebUtils.checkStr(id)) {
                return WebUtils.flushFailure("找不到要修改的规格");
            }
            GoodsSpecs goodsSpecs = goodsSpecsRepository.getById(id);
            if (goodsSpecs == null) {
                return WebUtils.flushFailure("找不到要修改的规格");
            }
            String skuCode = jsonObject.getString("skuCode");
            if (!WebUtils.checkStr(skuCode)) {
                return WebUtils.flushFailure("没有唯一编码，无法添加");
            }
            if (!skuCode.equals(goodsSpecs.getSkuCode())) {
                String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
                Integer count = goodsSpecsRepository.countSkuCode(skuCode, companyId, GoodsSpecs.STATUS_DELETE, goodsSpecs.getGoods().getGoodsType().getIsProduct());
                if (count > 0) {
                    return WebUtils.flushFailure("唯一编码“" + skuCode + "”已经被占用了，无法添加此规格");
                }
                goodsSpecs.setSkuCode(skuCode);
            }
            String name = jsonObject.getString("name");
            goodsSpecs.setName(name);
            String specsNames = jsonObject.getString("specsNames");
            goodsSpecs.setSpecsNames(specsNames);
            String specsValues = jsonObject.getString("specsValues");
            goodsSpecs.setSpecsValues(specsValues);
            String memo = jsonObject.getString("memo");
            goodsSpecs.setMemo(memo);
            String imgId = jsonObject.getString("imgId");
            goodsSpecs.setImgId(imgId);
            String imgUrl = jsonObject.getString("imgUrl");
            goodsSpecs.setImgUrl(imgUrl);

            goodsSpecs.setStatus(GoodsSpecs.STATUS_RUNNING);
            String loginId = WebUtils.getSessionValue(request, WebUtils.LOGIN_USER_KEY);
            Employee modifier = new Employee();
            modifier.setId(loginId);
            goodsSpecs.setModifier(modifier);
            goodsSpecs.setLastModifiedTime(new Date());

            goodsSpecsRepository.save(goodsSpecs);

            JpaQueryBuilder<GoodsSpecsPropValues> pb = Specifications.and();
            pb.eq("goodsSpecs.id", id);
            List<GoodsSpecsPropValues> all = goodsSpecsPropValuesRepository.findAll(pb.build());
            goodsSpecsPropValuesRepository.deleteAll(all);

            JSONArray propList = jsonObject.getJSONArray("propList");
            List<GoodsSpecsPropValues> list = new ArrayList<>();
            for (int i = 0; i < propList.size(); i++) {
                JSONObject prop = propList.getJSONObject(i);

                String pid = prop.getString("id");
                String code = prop.getString("code");
                String pValue = prop.getString("value");

                GoodsSpecsPropValues goodsSpecsPropValues = new GoodsSpecsPropValues();
                goodsSpecsPropValues.setGoods(goodsSpecs.getGoods());
                goodsSpecsPropValues.setGoodsSpecs(goodsSpecs);
                GoodsSpecsPropSetting setting = new GoodsSpecsPropSetting();
                setting.setId(pid);
                goodsSpecsPropValues.setGoodsSpecsPropSetting(setting);
                goodsSpecsPropValues.setCode(code);
                goodsSpecsPropValues.setValue(pValue);
                list.add(goodsSpecsPropValues);
            }
            goodsSpecsPropValuesRepository.saveAll(list);

            return WebUtils.flushSuccess();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return WebUtils.flushFailure("添加规格时，数据不能成功解析");
        }


    }


    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class)
    public ReplyObj del(HttpServletRequest request, String id) {
        try {
            delGoodsSpecsPropValues(id);
            goodsSpecsRepository.deleteById(id);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            GoodsSpecs goodsSpecs = goodsSpecsRepository.getOne(id);
            goodsSpecs.setStatus(GoodsSpecs.STATUS_DELETE);
            goodsSpecsRepository.save(goodsSpecs);
            return WebUtils.flushSuccess();
        }
    }


    /**
     * 删除规格属性配置的对应值
     *
     * @param goodsSpecsId 规格id
     */
    private void delGoodsSpecsPropValues(String goodsSpecsId) {
        JpaQueryBuilder<GoodsSpecsPropValues> pb = Specifications.and();
        pb.eq("goodsSpecs.id", goodsSpecsId);
        List<GoodsSpecsPropValues> all = goodsSpecsPropValuesRepository.findAll(pb.build());
        goodsSpecsPropValuesRepository.deleteAll(all);
    }


}
